//
//  JXHFindEmoticon.swift
//  JXHSinaWeiBo
//
//  Created by juxiaohui on 16/11/10.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit

class JXHFindEmoticon: NSObject {
    
    static let shareInstance : JXHFindEmoticon = JXHFindEmoticon()

    fileprivate lazy var manager : JXHEmoticonManager = JXHEmoticonManager.init()
    
    //匹配表情
    func findAttrString(statusText : String?,font : UIFont) -> NSMutableAttributedString? {
        
        guard let statusText = statusText else {
            return nil
        }
        
        //创建匹配规则
        let pattern = "\\[.*?\\]"
        //创建正则表达式
        guard let regex = try? NSRegularExpression.init(pattern: pattern, options: []) else {
            return nil
        }
        //开始匹配
        let results = regex.matches(in: statusText, options: [], range: NSRange.init(location: 0, length: statusText.characters.count))
        let attMstr = NSMutableAttributedString.init(string: statusText)
        
        for (_,result) in results.enumerated().reversed() {
            
            let chs = (statusText as NSString).substring(with: result.range)
            //根据chs获取图片路径
            guard  let pngPath = findPngPath(chs: chs) else {
                return nil
            }
            // 图文混排
            let attachment = NSTextAttachment.init()
            attachment.image = UIImage.init(named: pngPath)
    
            attachment.bounds = CGRect.init(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
            
            let attImageStr = NSAttributedString.init(attachment: attachment)
            //将属性字符串替换到原来的位置
            attMstr.replaceCharacters(in: result.range, with: attImageStr)
        }
        return attMstr;
    }
    
    //从后面开始替换，保持位置不变
   fileprivate func findPngPath(chs : String) -> String? {
        for package in manager.packages {
            for emoticon in package.emoticons {
                if emoticon.chs == chs {
                    return emoticon.pngPath
                }
            }
        }
        return nil
    }
}
